<?php

/*
 *
 */
define('COUNTER_PREFIX', 'counter_');
class QuickLite extends SQLiteDatabase
{
	// overwriting of SQLiteDatabase::arrayQuery() to always get associative result
	public function arrayQuery($query)
	{
		$this->_lastIds = array();
		return parent::arrayQuery($query, SQLITE_ASSOC);
	}
	
	// Escape SQLite string
	public static function escapeString($str)
	{
		return sqlite_escape_string($str);
	}
	
	private $_lastIds;
	
	// Unique id generator
	public function getNextId($name)
	{
		$query  = debug('SELECT value FROM id WHERE name="'.$name.'" LIMIT 1', 'SQL', JGLIB_DEBUG_SQLL);
		$result = debug($this->arrayQuery($query), 'Result SQL', JGLIB_DEBUG_SQLL);
		if(empty($result))
		{
			$value = 1;
			$new = true;
		}
		else
		{
			$value = (int)$result[0]['value'];
		}
		
		$query = debug('UPDATE id SET value='.($value+1).' WHERE name="'.$name.'"', 'SQL', JGLIB_DEBUG_SQLL);
		if(isset($new))
		{
			$query = 'INSERT INTO id (name, value) VALUES("'.$name.'",2)';
		}
		
		$this->queryExec($query);
		
		$this->_lastIds[$name] = $value;
		return $value;
	}
	
	// Get the last unique generated id
	public function getLastId($name)
	{
		if(isset($this->_lastIds[$name]))
		{
			return $this->_lastIds[$name];
		}
		
		$query  = debug('SELECT value FROM id WHERE name="'.$name.'" LIMIT 1', 'SQL', JGLIB_DEBUG_SQLL);
		$result = debug($this->arrayQuery($query), 'Result SQL', JGLIB_DEBUG_SQLL);
		if(!empty($result))
		{
			return (int)$result[0]['value'];
		}
		
		return 0;
	}
	
	// Count emulation to allow faster count :D
	public function counterIncrement($name)
	{
		return ($this->getNextId(COUNTER_PREFIX.$name)-1);
	}
	
	// Part of the count emulation
	public function getCounter($name)
	{
		return ($this->getLastId(COUNTER_PREFIX.$name)-1);
	}
	
	// Part of the count emulation
	public function counterDecrement($name)
	{
		$name = COUNTER_PREFIX.$name;
		$query  = debug('SELECT value FROM id WHERE name="'.$name.'" LIMIT 1', 'SQL', JGLIB_DEBUG_SQLL);
		$result = debug($this->arrayQuery($query), 'Result SQL', JGLIB_DEBUG_SQLL);
		if(empty($result))
		{
			$value = 1;
		}
		else
		{
			$value = (int)$result[0]['value'];
		}
		
		$query = debug('UPDATE id SET value='.($value-1).' WHERE name="'.$name.'"', 'SQL', JGLIB_DEBUG_SQLL);
		$this->queryExec($query);
		
		$this->_lastIds[$name] = $value;
		return ($value-1);
	}
	
	public function setup()
	{
		@$this->queryExec('DROP TABLE id;');
				$id = "
CREATE TABLE id (
	name VARCHAR NOT NULL PRIMARY KEY,
	value INT NOT NULL
);";
		$this->queryExec($id);
	}
}
